// 获取 URL 查询参数的函数
function getQueryParameter(name) {
    var urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// 获取产品名和产品 ID
var productName = getQueryParameter('productName');
var productId = getQueryParameter('productId');

// 显示产品名
document.getElementById("product-name").textContent = productName || '未选择产品';

// 更新某个元素的 data-id 属性
document.getElementById("product-name").setAttribute("data-id", productId || '');


$('.submit').click(function () {
    // 获取 selected-date-text 元素
    const selectedDateText = document.getElementById("selected-date-text");

// 创建 MutationObserver 实例
    const observer = new MutationObserver(function(mutations) {
        // 当 selected-date-text 的内容变化时，会调用这个回调函数
        mutations.forEach(function(mutation) {
            if (mutation.type === "childList") {
                // 校验日期
                validateDate(selectedDateText);
            }
        });
    });

// 配置观察的内容
    const config = {
        childList: true,   // 监听子节点变化，即文本内容变化
        subtree: true      // 监听整个子树
    };

// 开始监听 selected-date-text
    observer.observe(selectedDateText, config);

// 校验日期的函数
    function validateDate(input) {
        const errorMsg = document.getElementById("date-error");

        if (!input.textContent.trim() || input.textContent === "未选择") {
            errorMsg.style.display = "inline";
            errorMsg.textContent = "请选择日期";
            input.classList.add("invalid");
        } else {
            errorMsg.style.display = "none";
            input.classList.remove("invalid");
        }
    }


    function validateTimeSlot(select) {
        const errorMsg = document.getElementById("timeSlot-error");
        if (!select.value) {
            errorMsg.style.display = "inline";
            errorMsg.textContent = "请选择时间段";
            select.classList.add("invalid");
        } else {
            errorMsg.style.display = "none";
            select.classList.remove("invalid");
        }
    }

    function validateBeautician(select) {
        const errorMsg = document.getElementById("beautician-error");
        if (!select.value) {
            errorMsg.style.display = "inline";
            errorMsg.textContent = "请选择美容师";
            select.classList.add("invalid");
        } else {
            errorMsg.style.display = "none";
            select.classList.remove("invalid");
        }
    }


    function validateName(input) {
        const errorMsg = input.nextElementSibling;
        if (!input.value.trim()) {
            input.classList.add("invalid");
            errorMsg.style.display = "inline";
            errorMsg.textContent = "姓名不能为空";
        } else {
            input.classList.remove("invalid");
            errorMsg.style.display = "none";
        }
    }

    function validateTel(input) {
        const errorMsg = input.nextElementSibling;
        const telRegex = /^1[3-9]\d{9}$/;
        if (!telRegex.test(input.value.trim())) {
            input.classList.add("invalid");
            errorMsg.style.display = "inline";
            errorMsg.textContent = "请输入有效的手机号";
        } else {
            input.classList.remove("invalid");
            errorMsg.style.display = "none";
        }
    }

    function validateRemark(input) {
        const errorMsg = input.nextElementSibling;
        if (input.value.trim().length > 50) {
            input.classList.add("invalid");
            errorMsg.style.display = "inline";
            errorMsg.textContent = "备注不能超过50个字符";
        } else {
            input.classList.remove("invalid");
            errorMsg.style.display = "none";
        }
    }

    // 调用校验函数
    validateDate(document.getElementById("selected-date-text"));
    validateTimeSlot(document.getElementById("timeSlot"));
    validateBeautician(document.getElementById("beautician"));

    const nameInput = document.querySelector(".name");
    const telInput = document.querySelector(".tel");
    const remarkInput = document.querySelector(".remark");

    validateName(nameInput);
    validateTel(telInput);
    validateRemark(remarkInput);

    // 检查是否有无效字段
    const invalidInputs = document.querySelectorAll(".invalid");
    const errorMessages = document.querySelectorAll(".error-msg[style='display: inline;']");

    if (invalidInputs.length > 0 || errorMessages.length > 0) {
        // 如果存在无效字段，直接阻止提交
        return false;
    }

    // 收集数据
    const service_id = $('#product-name').attr('data-id');
    const service_date = $('.service_date').text();
    const service_period = $('.service_period option:selected').text();
    const beau_id = $('.beauName').val();
    const fullName = $('.name').val();
    const tel = $('.tel').val();
    const remark = $('.remark').val();
    // 提交 AJAX 请求
    const contextPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 1));
    const url = `${contextPath}/ReservationServlet`;

    $.ajax({
        url: url,
        type: 'POST',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: {
            name: fullName,
            tel: tel,
            service_id:service_id,
            beau_id:beau_id,
            dateSelect: service_date,
            period: service_period,
            remark: remark,
            action: 'add',
        },
        success: function (data, status) {
            if (status === 'success') {
                // 替换为页面成功提示
                alert("操作成功！");
                location.href = '../user/myUser.jsp';
            }
        },
        error: function () {
            // 替换为页面错误提示
            alert("操作失败！网络异常！");
        },
    });
});

// 获取美容师的函数
function loadBeauticians(serviceId) {
    // 发送 AJAX 请求
    $.ajax({
        url: '../getBeauByServiceIdServlet',  // 后端的Servlet URL
        type: 'GET',
        data: { serviceId: serviceId },
        success: function(response) {
            // 获取美容师选择框
            var beauticianSelect = document.getElementById("beautician");

            // 清空当前选择框
            beauticianSelect.innerHTML = '<option value="">请选择美容师</option>';

            // 动态添加美容师选项
            response.forEach(function(beautician) {
                var option = document.createElement("option");
                option.value = beautician.id;
                option.textContent = beautician.name;
                beauticianSelect.appendChild(option);
            });
        },
        error: function(xhr, status, error) {
            console.error("请求失败:", error);
        }
    });
}

// 页面加载时，加载美容师数据
window.onload = function() {
    // 获取项目的data-id值
    var serviceId = document.getElementById("product-name").getAttribute("data-id");

    // 加载对应的美容师
    loadBeauticians(serviceId);
};

document.addEventListener('DOMContentLoaded', function () {
    const dateText = document.getElementById('selected-date-text'); // 选中的日期
    const timeSelect = document.getElementById('timeSlot'); // 时间段选择器
    const timeOptions = timeSelect.querySelectorAll('option[data-time]'); // 时间段选项

    // 更新时间段状态
    function updateTimeSlots() {
        const selectedDateText = dateText.textContent.trim(); // 获取日期内容
        if (selectedDateText === '未选择' || !selectedDateText) {
            // 未选择日期时，所有时间段可选
            timeOptions.forEach(option => {
                option.disabled = false;
                option.textContent = option.textContent.replace(' (已过期)', '');
            });
            return;
        }

        // 将所选日期转换为 Date 对象
        const selectedDate = new Date(selectedDateText);
        if (isNaN(selectedDate.getTime())) {
            console.error('日期格式错误：', selectedDateText);
            return;
        }

        const currentDate = new Date(); // 当前系统时间

        timeOptions.forEach(option => {
            option.disabled = false; // 重置状态
            option.textContent = option.textContent.replace(' (已过期)', '');

            const [hours, minutes] = option.getAttribute('data-time').split(':');
            const optionTime = new Date(selectedDate); // 创建选项时间
            optionTime.setHours(parseInt(hours, 10), parseInt(minutes, 10), 0);

            if (
                selectedDate.toDateString() === currentDate.toDateString() && // 当天
                currentDate > optionTime // 时间已过
            ) {
                option.disabled = true;
                option.textContent += ' (已过期)';
            }
        });
    }

    // 使用 MutationObserver 监听日期变化
    const observer = new MutationObserver(updateTimeSlots);

    // 配置 MutationObserver 监听目标
    observer.observe(dateText, { childList: true, subtree: true, characterData: true });

    // 初始化时手动调用一次
    updateTimeSlots();
});
